home *** CD-ROM | disk | FTP | other *** search
- /* DEMO2.C - MicroThread demonstration written by I H Ting
-
- This example demonstrates basic multi-threading. Three threads
- are created initially. One waits for user input at the keyboard,
- another update the status on the screen, and another to bounce
- a 'ball' around the screen. Pressing 'a' will cause a new
- 'ball-bouncing' thread to be added each time until the maximum
- number of threads is reached. Pressing 'q' stops the program.
- */
-
- #include "mthread.h"
-
- #define TRAIL_LEN 15
-
- int numBalls=0;
-
-
- /* Ball bouncing routine */
- void BounceBall(void)
- {
- char ball='o';
- long x,y,ix,iy;
- int xBall, yBall, xTrail[TRAIL_LEN], yTrail[TRAIL_LEN],
- iBall, iTrail, iBlank;
-
- for(iTrail=0; iTrail<TRAIL_LEN; iTrail++){
- xTrail[iTrail]=2;
- yTrail[iTrail]=2;
- }
- x=y=200;
- ix=iy=100;
- iBall=TRAIL_LEN-1;
- iTrail=TRAIL_LEN-2;
- iBlank=0;
- while(1){
- xBall=(int)(x/100);
- yBall=(int)(y/100);
- if(xTrail[iTrail]!=xBall || yTrail[iTrail]!=yBall){
- MTxyputc(xBall,yBall,ball);
- MTxyputc(xTrail[iTrail],yTrail[iTrail],'.');
- MTxyputc(xTrail[iBlank],yTrail[iBlank],' ');
- xTrail[iBall]=xBall;
- yTrail[iBall]=yBall;
- iBall = (iBall+1) % TRAIL_LEN;
- iBlank = (iBlank+1) % TRAIL_LEN;
- iTrail = (iTrail+1) % TRAIL_LEN;
- }
- x += ix;
- y += iy;
- ix = x > 7900 ? -MTrandom(100) : ix;
- ix = x < 200 ? MTrandom(100) : ix;
- iy = y > 2300 ? -MTrandom(100) : iy;
- iy = y < 300 ? MTrandom(100) : iy;
- }
- }
-
-
- void InfoThread(void)
- {
- MTxyputs(1,1, "MicroThread Demonstration. Press 'a' to add an ball, 'q' to quit");
- while(1){
- MTxyprintf(1,25,"Number of balls : %d", numBalls);
- }
- }
-
-
-
- /* Waits for the key 'q' to be pressed to end multitasking */
- void InputThread(void)
- {
- int retval, priority;
-
- while(1){
- if (MTgetch()=='a'){
- priority = numBalls % 5 +1;
- retval = MTAddThread(BounceBall,priority);
- if(retval) numBalls++;
- }
- if (MTgetch()=='q'){
- MTEndMultiThreading();
- }
- }
- }
-
-
-
- /* the main program */
- void main(void)
- {
- MTInitialise();
- MTAddThread(InfoThread,1);
- MTAddThread(InputThread,5);
- MTAddThread(BounceBall,1);
- numBalls++;
- MTclrscr();
- MTStartMultiThreading();
- MTclrscr();
- }
-
-
-